App({
  onLaunch: function(e) {
    wx.getSystemInfo({
      success: function(res) {
        console.log(res)
        let platform = res.platform;
        console.log("platform" + platform);
        if (platform == "android") {
          platform = 1;
        } else if (platform == "ios") {
          platform = 0;
        } else {
          platform = 1; //其他包括模拟器PC端
        }
        wx.setStorageSync("deviceInfo", res) //手机设备信息
        wx.setStorageSync("platform", platform) //客户端平台
      }
    })
    wx.setStorageSync("playstatus", 0) //播放状态
    wx.setStorageSync("jianbao", undefined)
    wx.setStorageSync("sex", undefined)
    // wx.setStorageSync("userId", "40248")
    this.checkEquipmentState();
    var userInfo;
    var ttbtSession;
    var vm = this
    if (userInfo = wx.getStorageSync('userInfo')) {
      this.globalData.userInfo = userInfo;
      this.globalData.userId = wx.getStorageSync('userId')
    }
    if (ttbtSession = wx.getStorageSync('ttbtSession')) {
      this.globalData.ttbtSession = ttbtSession
    }

    wx.onNetworkStatusChange(function(res) {
      if (res.isConnected) {
        showauthbtn()
      }
    })
  },
  globalData: {
    // https: "http://192.168.1.244:8082/gox-ttbt/", //接口调用地址
    // https: "https://www.blistening.cn/",
    // https: "http://192.168.1.194:8083/", //接口调用地址2
    https: "https://blistening.cn/",
    // https: "https://www.blistening.cn/",
    source: "http://source.blistening.cn/bt_source/ttbt/", //资源图片地址
    authImg: "http://source.blistening.cn/bt_source/ttbt/red_packet/auth_wind.png", //授权红包资源图片
    shareurl: "http://source.blistening.cn/bt_source/ttbt/ttbt_share_pic_500.png",
    userInfo: null, //用户基本信息
    ttbtSession: null, //自定义登录态
    backType: null, //登录后返回之前的页面
    userId: null, //服务端返回的唯一id
    search_app_name: '天天必听',
    collectSuceessTxt:'去记录-收藏查看详情',
    isMaintain: "0" // 之前线上 "1"
  },

  //上报用户登录的设备信息
  saveDeviceInfo: function(userId) {
    let that = this;
    let data = {
      deviceInfo: JSON.stringify(wx.getStorageSync("deviceInfo")),
      userId: userId
    };
    that.request(getApp().globalData.https + "device/saveDeviceInfo",
      "post", data,
      function(res) {
        if (res.code == 0) {} else {
          console.log("失败")
        }
      },
      function(res) {
        console.log(res)
      });
  },

  //检查后台配置是否启用ios
  checkEquipmentState: function() {
    console.log("=======" + wx.getStorageSync("platform"))
    var data = {
      platform: wx.getStorageSync("platform")
    }
    this.request(this.globalData.https + "trueOrFalseResource/getPlatformFlag",
      "get", data,
      function(res) {
        if (res.code == 0) {
          // flg(string, optional): 状态 0.不显示 1.显示,
          if (res.data.flg == "0") {
            wx.setStorageSync("iPhone", "1")
          } else {
            wx.setStorageSync("iPhone", "-1")
          }
        } else {
          showMsgToast(res.message)
        }
      },
      function(res) {});
  },

  onShow: function(e) {
    wx.setStorage({
      key: 'scene',
      data: e.scene,
    })
    wx.setStorage({
      key: 'shareTicket',
      data: e.shareTicket,
    })
  },

  showMsgToast: function(msg) {
    wx.showToast({
      title: msg,
      icon: "none"
    })
  },

  showMsgToastLong: function(msg) {
    wx.showToast({
      title: msg,
      icon: "none",
      duration: 2000
    })
  },
  //第二步
  login: function() {
    var that = this;
    wx.showLoading({
      title: '授权中',
    })
    wx.login({
      success: function(res) {
        // 发送 res.code 到后台换取 userId, ttbtSession, unionId
        if (res.code) {
          that.getEncDataTOUnionid(res.code);
          //   that.sendCode(res.code);
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      },
      fail: function(res) {
        console.log('login fail: ' + res.errMsg);
      }
    })
  },

  //获取用户加密数据，发送给服务端进行解析用户 Unionid
  getEncDataTOUnionid: function(code) {
    var that = this;　　　　
    wx.getUserInfo({　　　　　　
      withCredentials: true,
      success: function(res) {
        that.sendCode(code, res.encryptedData, res.iv);　　　　　　
      }　　　　
    })　
  },

  //第二步
  // 向服务器发送微信登录返回的code,获取登录态
  sendCode: function(code, encryptedData, iv) { //
    var that = this;
    var clientUserInfo = that.globalData.userInfo //登录后客户端获取用户基本信息
    var channel = wx.getStorageSync("channel");
    var data
    //判断是不是被邀请用户
    var fromid = wx.getStorageSync("fromid");
    if (channel == undefined) {
      data = {
        channel: "",
        wxNickname: clientUserInfo.nickName,
        wxGender: clientUserInfo.gender,
        wxAvatarUrl: clientUserInfo.avatarUrl,
        wxProvince: clientUserInfo.province,
        wxCity: clientUserInfo.city,
        shareUserId: fromid,
        platform: wx.getStorageSync("platform"),
        wxEncryptedData: encryptedData,
        wxIv: iv,
      }
    } else {
      data = {
        channel: channel,
        wxNickname: clientUserInfo.nickName,
        wxGender: clientUserInfo.gender,
        wxAvatarUrl: clientUserInfo.avatarUrl,
        wxProvince: clientUserInfo.province,
        wxCity: clientUserInfo.city,
        shareUserId: fromid,
        platform: wx.getStorageSync("platform"),
        wxEncryptedData: encryptedData,
        wxIv: iv,
      }
    }


    that.requestLoading(getApp().globalData.https + "weixinResource/openId/" + code, //将调用登录接口
      "post", data, "授权中...",
      function(res) {
        //获取到用户凭证 存儲 3rd_session 
        var serviceUserInfo = res.data //获取服务端返回的登录信息
        if (res.code == 0) {
          that.globalData.userId = serviceUserInfo.userId
          that.globalData.ttbtSession = serviceUserInfo.ttbtSession
          wx.setStorageSync("ttbtSession", serviceUserInfo.ttbtSession)
          wx.setStorageSync("userId", serviceUserInfo.userId)
          if (res.data.firstAuth) {
            wx.setStorageSync("firstAuth", "1")
          } else {
            wx.setStorageSync("firstAuth", "-1")
          }
          wx.navigateBack()
          console.log("用户登录成功")
          let pages = getCurrentPages();
          var currPage = pages[pages.length - 1]; //当前页
          if (currPage != undefined) {
            currPage.setData({
              showAuth: false,
              showAuth2: false
            })
          }
          currPage.onShow();
          that.saveDeviceInfo(serviceUserInfo.userId); //调用方法保存设备信息
        } else {
          console.log("用户登录失败")
        }
      },
      function(res) {
        console.log(res)
      });
  },
  //第一步页面调用
  checkLogin: function() { //检查用户是否已登录
    wx.showLoading({
      title: "加载中..."
    })
    var that = this;
    try {
      var ttbtSession = wx.getStorageSync('ttbtSession');
      //   console.log(ttbtSession)
      if (ttbtSession) {
        // 检查 session_key 是否过期
        wx.checkSession({
          // session_key 有效(未过期)
          success: function() {
            // console.log("微信登录态有效")
            // 业务逻辑处理
            wx.hideLoading();
          },
          // session_key 过期
          fail: function() {
            console.log("微信登录态失效")
            var page = getCurrentPages();
            // page.setData({
            //   showAuth: true
            // })
          }
        });
      } else {
        // 无skey，作为首次登录
        console.log("暂无用户登录态")
        // 显示授权弹窗
        var page = getCurrentPages();
        // page.setData({
        //   showAuth: true
        // })
        // that.toLoginHtml();
      }
    } catch (e) {}
  },


  //调用方法request ，，无loading加载框提示
  request: function(url, method, params, success, fail) {
    this.requestLoading(url, method, params, "", success, fail)
  },

  interceptOneRequest(url) {
    var lasturl = wx.getStorageSync("neturl");
    var lastnettime = wx.getStorageSync("nettime");
    if (lasturl != undefined) {
      if (lasturl == url && lastnettime != undefined) {
        if (new Date().getTime() - lastnettime <= 1000) {
          if (url != this.globalData.https +"/hd/listen/honbao"){
            this.showMsgToast("短时间内不能执行统一操作")
          }
          // this.showMsgToast("短时间内不能执行统一操作")
          return true;
        }
      }
    }
    wx.setStorageSync("neturl", url);
    wx.setStorageSync("nettime", new Date().getTime());
  },
  //调用方法requestLoading ，，会出现loading加载框提示
  // 网络请求
  // url:网络请求的url
  // params:请求参数
  // message:进度提示信息
  // success:成功的回调函数
  // fail：失败的回调
  requestLoading: function(url, method, params, message, success, fail) {
    var that = this
    if (url != this.globalData.https + "programResource/commonBannerList") {
      if (this.interceptOneRequest(url)) {
        return
      }
    }

    //判断如果用户未登陆显示弹窗类型
    if (wx.getStorageSync("userId") == "" || wx.getStorageSync("userId") == undefined) {
      // 显示授权弹窗
      console.log("检验弹窗...")
      var pages = getCurrentPages();
      var currPage = pages[pages.length - 1]; //当前页
      wx.request({
        url: that.globalData.https + "userResource/disableWallet",
        data: '',
        header: {
          'content-Type': 'application/json'
        },
        method: 'get',
        success: function(res) {
          if (res.data.code == 0) {
            //关闭游客模式，强制授权
            wx.setStorageSync("tourist", res.data.data.authPopup);
            // 1开启游客模式  0 关闭
            if (res.data.data.authPopup != "1") {
              //显示什么弹窗
              if (res.data.data.isFalse != undefined) {
                if (res.data.data.isFalse == "0") {
                  if (currPage != undefined) {
                    currPage.setData({
                      showAuth: true,
                      showAuth2: false
                    })
                  }
                } else {
                  if (currPage != undefined) {
                    currPage.setData({
                      showAuth: false,
                      showAuth2: true
                    })
                  }
                }

              }
            } else {
              //开启游客模式、非强制授权,判断显示什么类型弹窗
              if (res.data.data.isFalse == "0") {
                //用户看到
                wx.setStorageSync("authtype", "0")
              } else {
                //审查看到
                wx.setStorageSync("authtype", "1")
              }
            }

          }
        }
      })
    }
    wx.getNetworkType({
      success: function(res) {
        // 返回值
        var networkType = res.networkType
        if (networkType === "none") {
          wx.showLoading({
            title: "网络连接失败"
          })
          setTimeout(function() {
            wx.hideLoading()
          }, 2000)
        } else {
          wx.showNavigationBarLoading()
          if (message != "") {
            wx.showLoading({
              title: message,
            })
          }
          wx.request({
            url: url,
            data: params,
            header: {
              'content-Type': 'application/json'
            },
            method: method,
            success: function(res) {
              // console.log(url + JSON.stringify(res))
              wx.hideNavigationBarLoading()
              if (message != "") {
                setTimeout(function() {
                  wx.hideLoading()
                }, 200)
              }
              if (res.statusCode == 200) {
                success(res.data)
              }
            },
            fail: function(res) {
              //   console.log(res)
              wx.hideNavigationBarLoading()
              if (message != "") {
                wx.hideLoading()
              }
              wx.showLoading({
                title: "网络信号不佳"
              })
              setTimeout(function() {
                wx.hideLoading()
              }, 2000)
              fail()
            },
            complete: function(res) {
              //   console.log(res.data)
            },
          })
        }
      }
    })
  },

  //请求服务器返回结果提示框
  myDialog(res, message) {
    wx.showLoading({
      title: message
    })
    setTimeout(function() {
      wx.hideLoading()
    }, 2000)
  },

  /**
   * 登录页用户授权
   */
  authInfo: function(e) { //用户点击页面授权登录按钮调用
    var that = this;
    wx.hideLoading()
    this.showauthbtn();
    wx.getNetworkType({
      success: function(res) {
        // 返回值
        console.log("success")
        var networkType = res.networkType
        if (networkType === "none") {
          wx.showLoading({
            title: "网络连接失败"
          })
          setTimeout(function() {
            wx.hideLoading()
          }, 2000)
          that.showauthbtn();
        } else {
          wx.hideLoading()
          if (e.detail.userInfo) {
            //   console.log("用户信息获取=" + JSON.stringify(e.detail.userInfo))
            wx.setStorageSync("userInfo", e.detail.userInfo)
            that.globalData.userInfo = e.detail.userInfo; //全局变量用户信息
            //用户按了允许授权按钮 
            that.login();
          } else {
            //用户按了拒绝按钮
            that.showauthbtn();
            wx.showModal({
              title: '警告',
              content: '您点击了拒绝授权，将无法体验我们更多功能，请授权！',
              showCancel: false,
              confirmText: '返回授权',
              success: function(res) {
                if (res.confirm) {
                  console.log('用户点击了“返回授权”')
                }
              }
            })
          }
        }
      },
      complete: function() {}
    })

  },

  showauthbtn: function() {
    let pages = getCurrentPages();
    var currPage = pages[pages.length - 1]; //当前页
    currPage.setData({
      authbtn: false
    })
  },
  userInfoSetInSQL: function(userInfo) {
    wx.getStorage({
      key: 'third_Session',
      success: function(res) {
        wx.request({
          url: '',
          data: {
            third_Session: res.data,
            nickName: userInfo.nickName,
            avatarUrl: userInfo.avatarUrl,
            gender: userInfo.gender,
            province: userInfo.province,
            city: userInfo.city,
            country: userInfo.country
          },
          success: function(res) {}
        })
      }
    })
  },


  //秒 转 分秒
  s_to_hs: function(s) {
    //计算分钟
    //算法：将秒数除以60，然后下舍入，既得到分钟数
    var h;
    h = Math.floor(s / 60);
    //计算秒
    //算法：取得秒%60的余数，既得到秒数
    s = s % 60;
    //将变量转换为字符串
    h += '';
    s += '';
    //如果只有一位数，前面增加一个0
    h = (h.length == 1) ? '0' + h : h;
    s = (s.length == 1) ? '0' + s : s;
    return h + ':' + s;
  },
})